package com.lizard.schedule.ui.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;

import com.android.volley.VolleyError;
import com.lizard.schedule.R;
import com.lizard.schedule.manager.AccountManager;
import com.lizard.schedule.manager.observer.ObserverManager;
import com.lizard.schedule.manager.umeng.UmengManager;
import com.lizard.schedule.net.http.consts.ReturnCode;
import com.lizard.schedule.net.http.request.HttpRequestManager;
import com.lizard.schedule.net.http.request.HttpResponseListener;
import com.lizard.schedule.net.http.request.bean.LoginRequest;
import com.lizard.schedule.net.http.request.bean.ModifyPwdRequest;
import com.lizard.schedule.net.http.response.bean.LoginResponse;
import com.lizard.schedule.net.http.response.bean.ModifyPwdResponse;
import com.lizard.schedule.persistence.sharedpreferences.AccountPref;
import com.lizard.schedule.ui.activity.base.BaseActivity;
import com.lizard.schedule.ui.view.Titlebar;
import com.lizard.schedule.utils.RegexUtil;
import com.lizard.schedule.utils.ScheduleUtil;
import com.lizard.schedule.utils.StatusBarUtil;
import com.lizard.schedule.widget.ScheduleProgressDialog;
import com.lizard.schedule.widget.ScheduleToast;

/**
 * 修改密码
 */
public class ModifyPwdActivity extends BaseActivity{

    private EditText mOldPwdInput;

    private EditText mNewPwdInput;

    private EditText mConfirmPwdInput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_modify_pwd);

        // 设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this, R.color.schedule_blue);

        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView(){
        initTitle();
        mOldPwdInput = (EditText) findViewById(R.id.modify_pwd_old);
        mOldPwdInput.setTypeface(Typeface.DEFAULT);
        mOldPwdInput.setTransformationMethod(new PasswordTransformationMethod());
        mNewPwdInput = (EditText) findViewById(R.id.modify_pwd_new);
        mNewPwdInput.setTypeface(Typeface.DEFAULT);
        mNewPwdInput.setTransformationMethod(new PasswordTransformationMethod());
        mConfirmPwdInput = (EditText) findViewById(R.id.modify_pwd_confirm);
        mConfirmPwdInput.setTypeface(Typeface.DEFAULT);
        mConfirmPwdInput.setTransformationMethod(new PasswordTransformationMethod());
    }

    /**
     * 标题栏UI初始化
     */
    private void initTitle() {
        Titlebar titlebar = (Titlebar) findViewById(R.id.title_bar);

        titlebar.setLeftBtnClk(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                back();
            }
        });

        titlebar.setRightBtnClk(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                submitModify();
            }
        });
    }

    /**
     * 检查并提交修改
     */
    private void submitModify(){
        String oldPwd = mOldPwdInput.getText().toString().trim();
        String newPwd = mNewPwdInput.getText().toString().trim();
        String confirmPwd = mConfirmPwdInput.getText().toString().trim();

        if(TextUtils.isEmpty(oldPwd)){
            mOldPwdInput.setError(getString(R.string.input_old_pwd_hint));
            return;
        }

        if(TextUtils.isEmpty(newPwd) || newPwd.length() < 6 || newPwd.length() > 20){
            mNewPwdInput.setError(getString(R.string.please_input_new_pwd));
            return;
        }

        if(!RegexUtil.checkPassword(newPwd)){
            mNewPwdInput.setError(getString(R.string.new_pwd_error_chars_hint));
            return;
        }

        if(TextUtils.isEmpty(confirmPwd)){
            mConfirmPwdInput.setError(getString(R.string.please_input_confirm_new_pwd));
            return;
        }

        if(!newPwd.equals(confirmPwd)){
            mConfirmPwdInput.setError(getString(R.string.new_pwd_confirm_not_same));
            return;
        }

        // 提交修改
        submitModify(oldPwd, newPwd);
    }

    /**
     * 提交修改
     *
     * @param oldPwd
     * @param newPwd
     */
    private void submitModify(final String oldPwd, final String newPwd){
        final ScheduleProgressDialog.Builder progressDialogBuilder = new ScheduleProgressDialog.Builder(this)
                .setText(R.string.modify_progress_hint)
                .setCancelable(false);
        progressDialogBuilder.show();
        ModifyPwdRequest request = new ModifyPwdRequest();
        request.setPassword(oldPwd);
        request.setNewpwd(newPwd);
        HttpRequestManager.getInstance().request(request, new HttpResponseListener<ModifyPwdResponse>() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                progressDialogBuilder.cancel();
                ScheduleToast.makeScheduleToastS(R.string.network_error).show();
            }

            @Override
            public void onResponse(ModifyPwdResponse response) {
                progressDialogBuilder.cancel();
                if (ReturnCode.SUCCESS.equals(response.getReturnCode())) {    // 修改成功

                    // 保存密码和新token
                    AccountManager.getInstance().loginInit(
                            AccountManager.getInstance().getUsername(), newPwd, response.getToken(), 0);
                    back();
                    ScheduleToast.makeScheduleToastL(R.string.pwd_modify_success).show();

                } else if (ReturnCode.ORIGINAL_PWD_ERROR.equals(response.getReturnCode())) { // 原始密码错误
                    ScheduleToast.makeScheduleToastS(R.string.old_pwd_error).show();
                } else if (ReturnCode.TOKEN_EXPIRE.equals(response.getReturnCode())) { // token过期
                    // 重新登录
                    AccountManager.getInstance().verifyAccount(new HttpResponseListener<LoginResponse>() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            // 网络异常
                            ScheduleToast.makeScheduleToastS(R.string.network_error).show();
                        }

                        @Override
                        public void onResponse(LoginResponse response) {
                            if(ReturnCode.SUCCESS.equals(response.getReturnCode())){    // 成功
                                submitModify(oldPwd, newPwd);
                            }
                        }
                    });
                } else {     // 修改失败
                    ScheduleToast.makeScheduleToastS(R.string.modify_failed).show();
                }
            }
        });
    }

    /**
     * 返回
     */
    private void back(){
        ScheduleUtil.hideSoftInput(this);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        back();
    }
}
